package com.itheima.controller;

import com.github.pagehelper.Page;
import com.itheima.entity.MessageConstant;
import com.itheima.pojo.Todo;
import com.itheima.service.TodoService;
import com.itheima.utils.ResultUtil;
import com.itheima.vo.TodoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/todo")
@Api(tags = "待办事项相关接口")
@CrossOrigin
public class TodoController {

    @Autowired
    private TodoService todoService;

    /**
     * 添加代办事项
     *
     * @param todoVO
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("添加代办事项")
    public String add(@RequestBody(required = false) TodoVO todoVO, HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        //获取cookies
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            map.put(cookie.getName(), cookie.getValue());
        }
        //获取cookie中的adminId
        String adminId = map.get("adminId");
        todoService.add(todoVO, adminId);
        return ResultUtil.result("success", "代办事项添加成功");
    }

    /**
     * 删除代办事项
     *
     * @param todoVO
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除代办事项")
    public String delete(@RequestBody(required = false) TodoVO todoVO) {
        if (todoVO.getUid() == null || "".equals(todoVO.getUid())) {
            return ResultUtil.result("401", "代办事项删除失败,Uid不能为空");
        }
        todoService.delete(todoVO);
        return ResultUtil.result("success", "代办事项删除成功");
    }

    /**
     * 编辑代办事项
     *
     * @param todoVO
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation("编辑代办事项")
    public String edit(@RequestBody(required = false) TodoVO todoVO) {
        if (todoVO.getUid() == null || "".equals(todoVO.getUid())) {
            return ResultUtil.result("401", "代办事项编辑失败,Uid不能为空");
        }
        todoService.edit(todoVO);
        return ResultUtil.result("success", "代办事项编辑成功");
    }

    /**
     * 查询代办事项
     *
     * @param todoVO
     * @return
     */
    @PostMapping("/getList")
    @ApiOperation("查询代办事项")
    public String getList(@RequestBody(required = false) TodoVO todoVO) {
        Page<Todo> pageList = todoService.getListPage(todoVO);
        HashMap<String, Object> map = new HashMap<>();
        map.put("records",pageList);
        return ResultUtil.result("success", map);
    }

}
